from PyQt5 import QtCore, QtGui, QtWidgets, QtMultimedia
from PyQt5.QtWidgets import QApplication, QCheckBox, QGridLayout, QTreeWidgetItem, QLabel, QLineEdit, QDialog, QMessageBox
from PyQt5.Qt import Qt, QThread, QMutex, pyqtSignal
from ComboCheckBox import ComboCheckBox
from mainwindow import Ui_MainWindow
from pygame import time, mixer
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtCore import QSettings,QTimer,QDateTime
from plot import Plot_EEG, Plot_Music, Plot_EEG32
import subprocess
import fitz
import mido

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        # UI设置
        self.setupUi(self)
        QtWidgets.QApplication.setStyle('Fusion')
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.setWindowIcon(QIcon(":/img/img/favicon.ico"))
        self.setWindowTitle('脑波音乐')

        # 基本属性
        self.txt_path = ""                 # 加载的脑电波文件
        self.mid_path = ""                 # 获取的脑波音乐文件
        self.status = False                # 发送请求的状态
        self.music = False                 # 音乐是否加载完成
        self.expression = False            # 表情是否加载完成
        self.channel_number = 8            # 脑电通道数
        self.music_play = False
        self.settings = QSettings('Config.ini', QSettings.IniFormat)

        # 初始化下拉框
        content = ['通道' + str(i) for i in range(1, 9)]
        self.cb_channel = ComboCheckBox(self.tab_1, content)
        self.cb_channel.setGeometry(590, 340, 90, 20)
        self.cb_channel.signa.connect(self.draw_eeg)

        # 初始化画板
        self.plot_eeg = Plot_EEG(self.gb_plot)
        self.plot_music = Plot_Music(self.piano_plot)
        self.plot_realtime = Plot_EEG32(self.realtime_eeg, sample_step=1)
        self.plot_realtime.set_path(self.settings.value('General/eegpath'))

        # 初始化播放器
        mixer.init(44100, -16, 2, 1024)
        mixer.music.set_volume(50)
        mixer.music.load(self.settings.value('General/musicpath'))
        mus = mido.MidiFile(self.settings.value('General/musicpath'))
        self.progress_music.setMaximum(mus.length)

        # 初始化一个定时器
        self.timer = QTimer()
        self.timer.timeout.connect(self.progress_process)

        # 初始化调试信息
        self.debug_info_text = self.label_debug_info.text()
        self.label_debug_info.setText('')


# ==================================组件接口==================================================

    # 关闭窗口
    @QtCore.pyqtSlot()
    def on_bnt_close_clicked(self):
        self.close()

    # 最小化窗口
    @QtCore.pyqtSlot()
    def on_bnt_minimize_clicked(self):
        self.showMinimized()

    # 拖动窗口
    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()
            event.accept()
            self.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))

    def mouseMoveEvent(self, QMouseEvent):
        if QtCore.Qt.LeftButton and self.m_flag:
            self.move(QMouseEvent.globalPos() - self.m_Position)
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag = False
        self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))

    # 导入数据
    @QtCore.pyqtSlot()
    def on_btn_data_import_clicked(self):
        filename = QtWidgets.QFileDialog.getOpenFileName(
            self, "打开txt文件", "", "txt文件 (*.txt)")
        if filename[0] != '':
            self.txt_path = filename[0]
            self.draw_eeg([1])

    # 开始分析
    @QtCore.pyqtSlot()
    def on_btn_analyse_clicked(self):
        if self.txt_path != "":
            pix = QPixmap(":/img/img/happy.png")
            self.label_expression.setPixmap(pix)
            self.label_expression.setScaledContents(True)
            self.label_expression_2.setPixmap(pix)
            self.label_expression_2.setScaledContents(True)
            self.plot_music.plot()

    @QtCore.pyqtSlot()
    def on_btn_score_clicked(self):
        museScore = self.settings.value('General/MuseScore')
        musicpath = self.settings.value('General/musicpath')
        subprocess.call([museScore, "-o",
                         "test.pdf", musicpath], shell=True)
        doc = fitz.open('test.pdf')
        page = doc.load_page(0)
        cover = render_pdf_page(page, True)
        self.label_score.resize(cover.size())
        self.label_score.setPixmap(QPixmap(cover))
        self.tabWidget.setCurrentIndex(3)

    @QtCore.pyqtSlot()
    def on_btn_return_clicked(self):
        self.tabWidget.setCurrentIndex(2)

    @QtCore.pyqtSlot()
    def on_btn_channel_clicked(self):
        if self.channel_number == 8:
            self.channel_number = 32
            self.btn_channel.setStyleSheet('border-image: url(:/img/img/32.png)')
        elif self.channel_number == 32:
            self.channel_number = 8
            self.btn_channel.setStyleSheet('border-image: url(:/img/img/8.png)')

        content = ['通道' + str(i) for i in range(1, self.channel_number + 1)]
        self.cb_channel.changeitemlist(content)


    @QtCore.pyqtSlot()
    def on_btn_play_clicked(self):
        if self.music_play == False:
            self.btn_play.setStyleSheet('border-image: url(:/img/img/stop.png)')
            if mixer.music.get_pos() <= 0:
                mixer.music.play()
            else:
                mixer.music.unpause()
            self.timer.start(1000)     
            self.music_play = True
        else:
            self.btn_play.setStyleSheet('border-image: url(:/img/img/play.png)')
            mixer.music.pause()
            self.timer.stop()
            self.music_play = False

    @QtCore.pyqtSlot()
    def on_btn_connect_bluetooth_clicked(self):
        self.plot_realtime.change_channel([i for i in range(1, 33)])
        self.label_debug_info.setText(self.debug_info_text)
        self.label_status.setStyleSheet('border-image: url(:/img/img/32.png)')

    @QtCore.pyqtSlot()
    def on_btn_disconnect_bluetooth_clicked(self):
        self.plot_realtime.change_channel([])
        self.label_debug_info.setText('')
        self.label_status.setStyleSheet('border-image: url(:/img/img/status0.jpg)')


# ================================自定义方法=================================================
    # 绘图
    def draw_eeg(self, context):
        try:
            channels = [int(item[-1]) for item in context]
        except:
            channels = [1]

        if self.txt_path != "":
            self.plot_eeg.set_path(self.txt_path)
            self.plot_eeg.change_channel(channels)

    # 音乐进度条
    def progress_process(self):
        cur_time = mixer.music.get_pos() // 1000
        if cur_time <= 0:
            self.music_play = False
            self.timer.stop()
        self.progress_music.setValue(cur_time)
        if cur_time <= 0:
            self.label_progress.setText('00:00')
        else:
            self.label_progress.setText('%02d:%02d' % (cur_time // 60, cur_time % 60))

    # # 重置界面
    # def reset_request(self):
    #     self.label_emotion.setText("当前情绪评估：(请求中……)")
    #     self.label_music.setText("脑波音乐播放：(请求中……)")
    #     self.music = self.expression = False
    #     pix = QPixmap(":/img/img/query.png")
    #     self.label_expression.setPixmap(pix)
    #     self.label_expression.setScaledContents(True)

    # # 收到情绪的回复
    # def emotion_process(self, emotion):
    #     if emotion != "":
    #         print(emotion)
    #         self.label_emotion.setText("当前情绪评估:")
    #         self.expression = True
    #         if emotion == "positive":
    #             pix = QPixmap(":/img/img/happy.jfif")
    #         elif emotion == "neutral":
    #             pix = QPixmap(":/img/img/happy.jfif")
    #         elif emotion == "negative":
    #             pix = QPixmap(":/img/img/calm.jfif")
    #         self.label_expression.setPixmap(pix)
    #         self.label_expression.setScaledContents(True)
    #     else:
    #         self.label_emotion.setText("当前情绪评估:(网络错误)")

    # # 收到音乐的回复
    # def music_process(self, mid_path):
    #     if mid_path != "":
    #         print(mid_path)
    #         self.label_music.setText("脑波音乐播放:")
    #         self.music = True
    #         self.mid_path = mid_path
    #     else:
    #         self.label_music.setText("脑波音乐播放:(网络错误)")


def render_pdf_page(page_data, for_cover=False):
    zoom_matrix = fitz.Matrix(4, 4)
    if for_cover:
        zoom_matrix = fitz.Matrix(1, 1)
    pagePixmap = page_data.get_pixmap(
        matrix=zoom_matrix,
        alpha=False)
    imageFormat = QtGui.QImage.Format_RGB888
    pageQImage = QtGui.QImage(
        pagePixmap.samples,
        pagePixmap.width,
        pagePixmap.height,
        pagePixmap.stride,
        imageFormat)
    pixmap = QtGui.QPixmap()
    pixmap.convertFromImage(pageQImage)
    return pixmap
